package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.chlid

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.FragmentAgencyApplyingRestBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AreaItemBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.config.*
import com.example.shushiyunsst.util.HiDataBus
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.senon.modularapp.util.JssSpannableString
import java.lang.StringBuilder

class AgencyApplyingRestFragment : BaseDataBindingFragment<FragmentAgencyApplyingRestBinding>(),
    View.OnClickListener {

    companion object {

        fun newInstance(): AgencyApplyingRestFragment {
            val args = Bundle()
            val fragment = AgencyApplyingRestFragment()
            fragment.arguments = args
            return fragment
        }
    }


    private val icon = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private val motherIcon = AppGlobals.getApplication().getString(R.string.wallet_cml)

    private var mBean: AreaItemBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
    }


    override fun layoutId(): Int {
        return R.layout.fragment_agency_applying_rest
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewBinder.onViewClick = this

        HiDataBus.with<AreaItemBean>(AGENCY_APPLYING_AREA_Event)
            .observerSticky(this, false, {
                mBean = it
                showContent(it)
            })

        showMyWallet()

    }

    @SuppressLint("SetTextI18n")
    private fun showContent(it: AreaItemBean) {
        val areaName = getAreaName(it)

        viewBinder.title.text = JssSpannableString(
            _mActivity, "您申请 “${areaName}” 代理"
        ).first(areaName)
            .textColor(R.color.text_color_6)

        viewBinder.paying.text = "需支付 ${it.proxyFee} $icon"

        val target = "获得${it.scmlNums}枚${motherIcon}母币"
        viewBinder.rewarding.text = JssSpannableString(_mActivity, "同时可 $target")
            .first(target).textColor(R.color.PrimaryColor)

        viewBinder.statusDesc.text=JssSpannableString(
            _mActivity, "您申请的 “${areaName}” 代理已经被抢，\n建议您换个区域申抢"
        ).first(areaName)
            .textColor(R.color.text_color_6)
//        viewBinder.statusDesc.text = "您申请的 $areaName 代理已经被抢，\n建议您换个区域申抢"

        if (it.uid > 0) {
            viewBinder.statusDesc.visibility=View.VISIBLE
            viewBinder.applying.visibility=View.GONE
        }else{
            viewBinder.statusDesc.visibility=View.GONE
            viewBinder.applying.visibility=View.VISIBLE
        }

        showMyWallet()

    }

    private fun showMyWallet() {
        val target1 = "立即充值"

//        val balanceInfoBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()

        val allStr = "您当前可用余额 ${mBean?.sstBalance} $icon $target1"
        viewBinder.myWallet.text = JssSpannableString(_mActivity, allStr)
            .first(allStr).size(10)
            .first(target1).onClick(viewBinder.myWallet, R.color.PrimaryColor) {
                HiDataBus.with<String>(AGENCY_APPLYING_REST_ON_CHARGE)
                    .postStickyData("obj")
            }
    }

    override fun handMessage(msg: MessageWrap?) {
        if (msg?.message == TO_REFRESH_BALANCE_INFO) {
            showMyWallet()
        }

    }

    private fun getAreaName(item: AreaItemBean): String {

        val parentAreaName = if (item.parentArea != null)
            getParentAreaName(item.parentArea) else ""

        val areaName = item.areaName

//        return if (parentAreaName.isNotEmpty()) "${parentAreaName},$areaName" else areaName
        return when (parentAreaName.isNotEmpty()) {
            true -> if (parentAreaName.endsWith(","))
                "${parentAreaName}$areaName"
            else "${parentAreaName},$areaName"

            else -> areaName
        }
    }

    private fun getParentAreaName(item: AreaItemBean?): String {

        var string = StringBuilder()

        val parentArea = item?.parentArea

        if (parentArea?.areaName?.isNotEmpty() == true) {

            string.append(getParentAreaName(parentArea))

        }
        string.append(item?.areaName).append(",")

        if (string.isNotEmpty()) {

            if (string.indexOf(",") != string.lastIndexOf(",")) {
                string = string.deleteCharAt(string.lastIndexOf(","))
            }

        }
        return string.toString()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.bankIcon -> {
                HiDataBus.with<String>(AGENCY_APPLYING_REST_BACK_TO_AREA_LIST)
                    .postStickyData("")
            }
            R.id.applying -> {
                val mPop = PayingPassWordVerifyPop(_mActivity)
                XPopup.Builder(_mActivity)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            if (mPop.getIsOnVerifyPop()) {
                                if (mPop.getVerifyPop()) {
                                    agencyApplying()

                                } else {
                                    Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    })
                    .asCustom(mPop)
                    .show()
            }
        }
    }

    private fun agencyApplying() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        RestClient.builder()
            .url(R.string.applyProxyDo)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "aid" to "${mBean?.aid}",
                        "uid" to "${userInfo?.uid}"
                    )
                )
            )
            .success {
                normalShortToast(_mActivity, R.string.handover)

                viewBinder.title.text = ""
                viewBinder.paying.text = ""
                viewBinder.rewarding.text = ""

                getUserBalanceInfo(_mActivity)

                HiDataBus.with<String>(AGENCY_APPLYING_BACK_TO_INIT)
                    .postStickyData("")

                HiDataBus.with<String>(REQUIRE_REFRESH_PROXY_INDEX)
                    .postStickyData("")
            }
            .failure {
                normalShortToast(_mActivity, R.string.net_work_failed)
            }
            .error { _, msg ->
                normalShortToast(_mActivity, msg)
                HiDataBus.with<String>(AGENCY_APPLYING_BACK_TO_INIT)
                    .postStickyData("")
            }.build().post()
    }


}